const express = require("express")
const router = express.Router()
const mongoose = require("mongoose")
const md5 = require("md5")
// const jwt = require("jsonwebtoken")
const { readFile, writeFile } = require("../utlis/fs.js")
const { Schema } = mongoose
// 连接数据库
mongoose.connect("mongodb://127.0.0.1:27017/project").then((collection) => {
    console.log("mongo");
    console.log("数据库建立连接");
})
// 存入数据库数据类型
const userSchema = new Schema({
    username: String,
    password: String,
    tel: String
})
// 链接数据库里的集合
const User = mongoose.model("user", userSchema)
// 挂载路由业务 注册业务
router.post("/register", async (req, res, next) => {
    // 验证处理
    let { username, password, tel } = req.body
    if (username && password && tel) {
        // 验证用户名是否存在 数据库查询
        const one = await User.find({ username })
        console.log("reg", one);
        if (one.length > 0) {
            return res.json({ msg: "用户名已存在" })
        } else if (password.length <= 8 && password.length > 16) {
            return res.json({ msg: "密码格式不对请重新数据" })
        } else if (tel.length != 11) {
            return res.json({ msg: "手机号格式不对" })
        }
    } else {
        console.log("参数错误", username, password, tel);
        res.json({ msg: "注册失败" })
    }
    next()
}, async (req, res, next) => {
    try {
        const result = await User.create({
            username: req.body.username,
            password: md5(req.body.password),
            tel: req.body.tel
        })
        res.status(200).json({
            msg: "注册成功",
            code: 200,
            data: result
        })
    } catch (err) {
        throw err
    }
})
module.exports = router